package validators;

import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import javax.servlet.http.HttpSession;

import controllers.LocaleController;


public class EmailValidatorEdit implements Validator {
	/**
	 * Ienei Robert
	 * Validates the email when the admin creates a new user
	 */
	
	public EmailValidatorEdit() {
	}

	@Override
	public void validate(FacesContext context, UIComponent component,
			Object value) throws ValidatorException {

		String enteredEmail=(String) value;
        Pattern p = Pattern.compile("^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$");
        Matcher m = p.matcher(enteredEmail);
        boolean matchFound = m.matches();
        
		//internationalization
		HttpSession session = (HttpSession)
		FacesContext.getCurrentInstance().getExternalContext().getSession(true);
		LocaleController language = (LocaleController) session.getAttribute("language");
		String messageBundleName = "errorMessages.errors";
		if (language.getLanguage()=="ro"){
			messageBundleName += "_ro";
		}
		else if (language.getLanguage()=="hu"){
			messageBundleName += "_hu";
		}
		else if (language.getLanguage()=="de"){
			messageBundleName += "_de";
		}
		ResourceBundle messageBundle = ResourceBundle
				.getBundle(messageBundleName);
		//////////
		
        if (!matchFound) {
            FacesMessage message = new FacesMessage();
            message.setDetail(messageBundle.getString("email"));
            message.setSummary(messageBundle.getString("email"));
            throw new ValidatorException(message);
        }
       
	}

}
